package p.lodz.pl.poid.zad2.sound;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

public class SoundProcessor {

    public JPanel process() {
        File path = new File("sounds/bird.wav");

        LinkedList<File> files = new LinkedList<>();

        if (path.isDirectory()) {
            for (File f : path.listFiles()) {
                files.add(f);
            }
        } else {
            files.add(path);
        }

        for (File f : files) {
            try {
                // Open the wav file specified as the first argument
                WavFile wavFile = WavFile.openWavFile(f);
                // Display information about the wav file
//				wavFile.display();
                int numChannels = wavFile.getNumChannels();
                int signal_counter = 0;
                double[] signal = new double[(int) wavFile.getFramesRemaining() + 100]; // tutaj trzeba bedzie poprawic
                
                // Create a buffer of 100 frames
                double[] buffer = new double[100 * numChannels];
                int framesRead;
                do {
                    framesRead = wavFile.readFrames(buffer, 100);
                    for (int s = 0; s < framesRead * numChannels; s++) {
                        signal[signal_counter * 100 + s] = buffer[s];
                    }
                    signal_counter++;
                    
                } while (framesRead != 0);
                
                // Close the wavFile
                wavFile.close();
                
                double[][] d = new double[][]{signal};
                SoundProcessor m = new SoundProcessor();
                PlotWave pw = new PlotWave();
                String hz = f.getName().replaceAll("[^\\d]", "");
                
//				pw.plot(d, "sygnał wejściowy", 0);
                CepstrumAnalysis ca = new CepstrumAnalysis(signal, wavFile);
                FundamentalFrequencyFinder.Tuple max = ca.process();
                //System.out.printf("max= %d | %d \t f= %.2f %.2f\n",(int)(wavFile.getSampleRate() / Float.parseFloat(hz)),
                //		max.getRight(), Float.parseFloat(hz) , max.getLeft() );
                
                PlotWave plot = ca.plot();
                return plot.getPanel();
                //plot.close();
            } catch (IOException | WavFileException ex) {
                Logger.getLogger(SoundProcessor.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        return new JPanel();
    }

}
